#!/bin/bash

echo "=== MySQL 测试开始 ==="

# 启动 MySQL 服务
echo "启动 MySQL 服务..."
docker-compose -f mysql-compose.yml up -d

# 等待 MySQL 启动
echo "等待 MySQL 启动..."
sleep 20

# 检查容器状态
if ! docker ps | grep -q "test-mysql"; then
    echo "❌ MySQL 容器启动失败"
    exit 1
fi

echo "✅ MySQL 容器启动成功"

# 测试数据库连接
echo "测试数据库连接..."
if docker exec test-mysql mysql -utestuser -ptest123 -e "SELECT 1;" > /dev/null 2>&1; then
    echo "✅ 数据库连接成功"
else
    echo "❌ 数据库连接失败"
    docker-compose -f mysql-compose.yml logs mysql
    exit 1
fi

# 测试数据查询
echo "测试数据查询..."
RESULT=$(docker exec test-mysql mysql -utestuser -ptest123 test_db -e "SELECT COUNT(*) as count FROM test_table;" -s -N)
if [ "$RESULT" = "3" ]; then
    echo "✅ 数据查询成功，找到 $RESULT 条记录"
else
    echo "❌ 数据查询失败，期望 3 条记录，实际 $RESULT 条"
    exit 1
fi

# 测试数据插入
echo "测试数据插入..."
docker exec test-mysql mysql -utestuser -ptest123 test_db -e "INSERT INTO test_table (name, email) VALUES ('Test Insert', 'insert@test.com');"
NEW_COUNT=$(docker exec test-mysql mysql -utestuser -ptest123 test_db -e "SELECT COUNT(*) as count FROM test_table;" -s -N)
if [ "$NEW_COUNT" = "4" ]; then
    echo "✅ 数据插入成功"
else
    echo "❌ 数据插入失败"
    exit 1
fi

# 性能测试
echo "执行性能测试..."
docker exec test-mysql mysql -utestuser -ptest123 test_db -e "
CREATE TABLE perf_test (id INT AUTO_INCREMENT PRIMARY KEY, data VARCHAR(255));
INSERT INTO perf_test (data) SELECT CONCAT('data_', id) FROM test_table, test_table t2 LIMIT 1000;
SELECT COUNT(*) FROM perf_test;
DROP TABLE perf_test;
" > /dev/null 2>&1

if [ $? -eq 0 ]; then
    echo "✅ 性能测试通过"
else
    echo "❌ 性能测试失败"
fi

echo "=== MySQL 测试完成 ==="

# 选择是否停止服务
read -p "是否停止 MySQL 服务? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    docker-compose -f mysql-compose.yml down
    echo "MySQL 服务已停止"
fi